package com.wmz.impl;

import com.wmz.constant.AuthConstants;
import com.wmz.factory.LoginStrategyFactory;
import com.wmz.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wmz
 * @date 2024/7/2 21:00
 * @description 自定的认证流程
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求头中的登录类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        //判断loginType是否存在
        if(!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配！！！");
        }
        //判断请求来自哪一个类型：使用 【策略模式 + 工厂模式】 来实现不同系统的登录，
        //通过登录策略工厂来获取具体的登录策略对象
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }

        return instance.realLogin(username);
    }
}
